#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

int tickets = 1000;  // 可售票数
pthread_spinlock_t lock;  // 自旋锁

void *route(void *arg)
{
    char *id = (char *)arg;
    while (1)
    {
        pthread_spin_lock(&lock);  // 请求自旋锁
        if (tickets > 0)
        {
            usleep(1000);  // 模拟票务延迟
            printf("thread %s: %d tickets left\n", id, tickets--);
        }
        else
        {
            pthread_spin_unlock(&lock);  // 解锁
            break; 
        }
        pthread_spin_unlock(&lock);
    }
    return NULL;
}

int main(void)
{
    pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE);  // 初始化自旋锁
    pthread_t t1, t2, t3;

    // 创建四个线程
    pthread_create(&t1, NULL, route, (void *)"t1");
    pthread_create(&t2, NULL, route, (void *)"t2");
    pthread_create(&t3, NULL, route, (void *)"t3");

    // 等待所有线程执行完毕
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);

    pthread_spin_destroy(&lock);  // 销毁自旋锁
    return 0;
}